package com.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.common.Result;
import com.project.entity.User;
import com.project.mapper.UserMapper;
import com.project.redis.RedisCache;
import com.project.security.LoginUserInfo;
import com.project.service.UserService;
import com.project.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ao
 * @since 2024-04-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private AuthenticationManager authenticationManagerBean;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录接口
     */
    @Override
    public Result<?> login(User user) {
        // 获取 AuthenticationManager 的 authenticate 方法进行认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManagerBean.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            // 认证不通过
            throw new RuntimeException("登录失败!");
        }
        // 认证通过, 获取用户对象
        LoginUserInfo loginUser = (LoginUserInfo) authenticate.getPrincipal();

        // 拿到用户对象
        User userInfo = loginUser.getUser();

        // 拿到用户相关信息
        String roleType = userInfo.getRoleType();
        String username = userInfo.getUserName();
        Long userId = userInfo.getId();

        HashMap<String , Object> map = new HashMap<>();
        map.put("roleType", roleType);
        map.put("username", username); // 用户名
        map.put("userId", userId);

        String token = JwtUtil.createJWT(map);

        // 将 登录用户 存入 redis
        redisCache.setCacheObject(roleType + "-" + userId, loginUser);

        HashMap<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("roleType", roleType);
        result.put("name", username);

        return Result.success(result);
    }
}
